<pre class='metadata'>
Title: Resize Observer Module Level 1
Shortname: resize-observer
Level: 1
Status: ED
Prepare for TR: no
Work Status: Exploring
ED: https://drafts.csswg.org/resize-observer/
TR: https://www.w3.org/TR/resize-observer/
Previous Version: https://www.w3.org/TR/2020/WD-resize-observer-1-20200211/
Group: CSSWG
URL: https://drafts.csswg.org/resize-observer/
Editor: Oriol Brufau, Igalia, obrufau@igalia.com, w3cid 108473
Editor: Emilio Cobos Álvarez, Mozilla, emilio@mozilla.com, w3cid 106537
Abstract: This specification describes an API for observing changes to Element's size.
Markup Shorthands: markdown yes
</pre>
<pre class="anchors">
urlPrefix: https://www.w3.org/TR/CSS2/box.html
    url: #content-width; type: dfn; text: content width
urlPrefix: https://www.w3.org/TR/CSS2/box.html
    url: #content-height; type: dfn; text: content height
urlPrefix: https://drafts.csswg.org/css-box-3/
    url: #padding-physical; type: dfn; text: padding top
urlPrefix: https://drafts.csswg.org/css-box-3/
    url: #padding-physical; type: dfn; text: padding left
urlPrefix: https://www.w3.org/TR/CSS2/visuren.html; spec: CSS2;
    url: #x1; text: viewport; type: dfn;
urlPrefix: https://www.w3.org/TR/intersection-observer/
    url: #intersection-observer-interface; type: interface; text: IntersectionObserver
urlPrefix: https://www.w3.org/TR/SVG2/
    urlPrefix: coords.html
        url: #BoundingBoxes; type: dfn; text: bounding box
urlPrefix: https://www.w3.org/TR/SVG2/
    urlPrefix: types.html
        url: #InterfaceSVGGraphicsElement; type: dfn; text: SVGGraphicsElement
urlPrefix: https://www.w3.org/TR/css3-multicol/
    url: #; type: dfn; text: Multi-column
urlPrefix:  https://www.w3.org/TR/css-display-3/
    url: #propdef-display; type:dfn; text: display
urlPrefix: https://www.w3.org/TR/CSS21/box.html
    url: #box-border-area; type: dfn; text: box border area
urlPrefix:  https://drafts.csswg.org/css-box-3/
    url: #content-area; type: dfn; text: content area
urlPrefix:  https://www.w3.org/TR/cssom-view-1/
    url: #dom-window-devicepixelratio; type: dfn; text: devicePixelRatio
urlPrefix:  https://heycam.github.io/webidl/
    url: #idl-frozen-array; type: dfn; text: FrozenArray

</pre>
<pre class=link-defaults>
spec:dom; type:interface; text:Document
</pre>

<h2 id="intro">Introduction</h2>

<em>This section is non-normative.</em>

Responsive Web Components need to respond to {{Element}}'s
size changes. An example is an {{Element}} that displays a map:

* it displays a map by tiling its content box with {{Element}} tiles.

* when resized, it must redo the tiling.

Responsive Web Applications can already respond to <a>viewport</a> size changes.
This is done with CSS media queries, or {{Window}}'s {{Window/resize}} event.

The ResizeObserver API is an interface for observing changes
to Element's size. It is an {{Element}}'s
counterpart to {{Window}}'s {{Window/resize}} event.

ResizeObserver's notifications can be used to respond to changes in {{Element}}'s size. Some interesting facts about these observations:

* Observation will fire when watched Element is inserted/removed from DOM.

* Observation will fire when watched Element <a>display</a> gets set to none.

* Observations do not fire for non-replaced inline Elements.

* Observations will not be triggered by CSS transforms.

* Observation will fire when observation starts if Element is [being rendered](https://html.spec.whatwg.org/#being-rendered), and Element's size is not 0,0.

<div class="example">
  <pre highlight="html">
    &lt;canvas id="ellipse" style="display:block">&lt;/canvas>
    &lt;div id="menu" style="display:block;width:100px">
        &lt;img src="hamburger.jpg" style="width:24px;height:24px">
        &lt;p class="title">menu title&lt;/p>
    &lt;/div>
  </pre>
  <pre highlight="js">
    // In response to resize, paint an ellipse inside a canvas
    document.querySelector('#ellipse').handleResize = entry => {
        entry.target.width = entry.borderBoxSize[0].inlineSize;
        entry.target.height = entry.borderBoxSize[0].blockSize;
        let rx = Math.floor(entry.target.width / 2);
        let ry = Math.floor(entry.target.height / 2);
        let ctx = entry.target.getContext('2d');
        ctx.beginPath();
        ctx.ellipse(rx, ry, rx, ry, 0, 0, 2 * Math.PI);
        ctx.stroke();
    }

    // In response to resize, change title visibility depending on width
    document.querySelector('#menu').handleResize = entry => {
        let title = entry.target.querySelector('.title');
        if (entry.borderBoxSize[0].inlineSize < 40)
            title.style.display = 'none';
        else
            title.style.display = 'inline-block';
    }

    let ro = new ResizeObserver(entries => {
      for (let entry of entries) {
        let cs = window.getComputedStyle(entry.target);
        console.log('watching element:', entry.target);
        console.log(entry.contentRect.top, ' is ', cs.paddingTop);
        console.log(entry.contentRect.left, ' is ', cs.paddingLeft);
        console.log(entry.borderBoxSize[0].inlineSize, ' is ', cs.width);
        console.log(entry.borderBoxSize[0].blockSize, ' is ', cs.height);
        if (entry.target.handleResize)
            entry.target.handleResize(entry);
      }
    });

    ro.observe(document.querySelector('#ellipse'));
    ro.observe(document.querySelector('#menu'));
  </pre>
</div>

<h2 id="api">Resize Observer API</h2>

<h3 id="resize-observer-interface">ResizeObserver interface</h3>

The ResizeObserver interface is used to observe changes to {{Element}}'s
size.

It is modeled after {{MutationObserver}} and {{IntersectionObserver}}.

<pre class="idl">
    enum ResizeObserverBoxOptions {
        "border-box", "content-box", "device-pixel-content-box"
    };
</pre>

ResizeObserver can observe different kinds of CSS sizes:

* {{border-box}}  : size of <a>box border area</a> as defined in CSS2.
* {{content-box}} : size of <a>content area</a> as defined in CSS2.
* {{device-pixel-content-box}} : size of <a>content area</a> as defined in CSS2, in device pixels,
    before applying any CSS transforms on the element or its ancestors.
    This size must contain integer values.

<p class="note">
The {{device-pixel-content-box}} can be approximated by multiplying <a>devicePixelRatio</a> by the {{content-box}} size.
However, due to browser-specific subpixel snapping behavior,
authors cannot determine the correct way to round this scaled {{content-box}} size.
How a UA computes the device pixel box for an element is implementation-dependent.
One possible implementation could be to multiply the box size and position by the device pixel ratio,
then round both the resulting floating-point size and position of the box to integer values,
in a way that maximizes the quality of the rendered output.

Note that this size can be affected by position changes to the target,
and thus is typically more expensive to observe than the other sizes.
</p>

<pre class="idl">
    dictionary ResizeObserverOptions {
        ResizeObserverBoxOptions box = "content-box";
    };
</pre>

This section is non-normative. An author may desire to observe more than one CSS box.
In this case, author will need to use multiple ResizeObservers.

<pre highlight="js">
    // Observe the content-box
    ro.observe(document.querySelector('#menu'), { box: 'content-box' });

    // Observe just the border box. Replaces previous observation.
    ro1.observe(document.querySelector('#menu'), { box: 'border-box' });
</pre>

<p class="note">This does not have any impact on which box dimensions are returned to the defined callback when the event is fired,
                it solely defines which box the author wishes to observe layout changes on.</p>

<pre class="idl">
[Exposed=(Window)]
interface ResizeObserver {
    constructor(ResizeObserverCallback callback);
    undefined observe(Element target, optional ResizeObserverOptions options = {});
    undefined unobserve(Element target);
    undefined disconnect();
};
</pre>

<div dfn-type="method" dfn-for="ResizeObserver">
    : <dfn constructor lt="ResizeObserver(callback)">new ResizeObserver(|callback|)</dfn>
    ::
        1. Let |this| be a new {{ResizeObserver}} object.

        2. Set |this|.{{ResizeObserver/[[callback]]}} internal slot to |callback|.

        3. Set |this|.{{ResizeObserver/[[observationTargets]]}} internal slot to an empty list.

        3. Add |this| to {{Document}}.{{Document/[[resizeObservers]]}} slot.

    : <dfn method>observe(|target|, |options|)</dfn>
    ::
        Adds target to the list of observed elements.

        1. If |target| is in {{ResizeObserver/[[observationTargets]]}} slot, call {{ResizeObserver/unobserve()}} with argument <var>target</var>.

        2. Let |observedBox| be the value of the {{ResizeObserverOptions/box}} dictionary member of <var>options</var>.

        3. Let |resizeObservation| be new {{ResizeObservation}}(<var>target</var>, <var>observedBox</var>).

        4. Add the |resizeObservation| to the {{ResizeObserver/[[observationTargets]]}} slot.

    :  <dfn method for="ResizeObserver">unobserve(|target|)</dfn>
    ::
        Removes |target| from the list of observed elements.

        1. Let |observation| be {{ResizeObservation}} in {{ResizeObserver/[[observationTargets]]}} whose target slot is |target|.

        2. If |observation| is not found, return.

        3. Remove |observation| from {{ResizeObserver/[[observationTargets]]}}.

    : <dfn method>disconnect()</dfn>
    ::
        1. Clear the {{ResizeObserver/[[observationTargets]]}} list.

        2. Clear the {{ResizeObserver/[[activeTargets]]}} list.

</div>

<h3 id="resize-observer-callback">ResizeObserverCallback</h3>

<pre class="idl">
callback ResizeObserverCallback = undefined (sequence&lt;ResizeObserverEntry> entries, ResizeObserver observer);
</pre>

This callback delivers {{ResizeObserver}}'s notifications. It is invoked by a
<a>broadcast active resize observations</a> algorithm.

<h3 id="resize-observer-entry-interface">ResizeObserverEntry</h3>

<pre class="idl">
[Exposed=Window]
interface ResizeObserverEntry {
    readonly attribute Element target;
    readonly attribute DOMRectReadOnly contentRect;
    readonly attribute FrozenArray&lt;ResizeObserverSize> borderBoxSize;
    readonly attribute FrozenArray&lt;ResizeObserverSize> contentBoxSize;
    readonly attribute FrozenArray&lt;ResizeObserverSize> devicePixelContentBoxSize;
};
</pre>

<p class="note">contentRect is from the incubation phase of ResizeObserver and is only included for current web compat reasons. It may be deprecated in future levels.</p>

<div dfn-type="attribute" dfn-for="ResizeObserverEntry">
    : <dfn>target</dfn>
    ::
        The {{Element}} whose size has changed.
    : <dfn>contentRect</dfn>
    ::
        {{Element}}'s <a>content rect</a> when {{ResizeObserverCallback}} is invoked.
    : <dfn>borderBoxSize</dfn>
    ::
        A {{FrozenArray}} containing the {{Element}}'s <a>border box</a> size when {{ResizeObserverCallback}} is invoked.
    : <dfn>contentBoxSize</dfn>
    ::
        A {{FrozenArray}} containing the {{Element}}'s <a>content rect</a> size when {{ResizeObserverCallback}} is invoked.
    : <dfn>devicePixelContentBoxSize</dfn>
    ::
        A {{FrozenArray}} containing the {{Element}}'s <a>content rect</a> size in integral device pixels when {{ResizeObserverCallback}} is invoked.

</div>

<p class="note">
The box size properties are exposed as {{FrozenArray}} in order to support elements that have multiple fragments,
which occur in <a>multi-column</a> scenarios.
However the current definitions of <a>content rect</a> and <a>border box</a>
do not mention how those boxes are affected by <a>multi-column</a> layout.
In this spec, there will only be a single ResizeObserverSize returned in the {{FrozenArray}},
which will correspond to the dimensions of the first column.
A future version of this spec will extend the returned {{FrozenArray}} to contain the per-fragment size information.
</p>

<pre class="idl">
    [Exposed=Window]
    interface ResizeObserverSize {
        readonly attribute unrestricted double inlineSize;
        readonly attribute unrestricted double blockSize;
    };
</pre>

<h2 id="processing-model">Processing Model</h2>

<h3 id="resize-observation-interface">ResizeObservation example struct</h3>

<p class="note">This section is non-normative. ResizeObservation is an example struct that can be used in implementation of Resize Observer. It is being
included here in order to help provide clarity during the processing model. It effectively holds observation information for a single {{Element}}. This
interface is not visible to Javascript.</p>

<pre class="idl extract">
interface ResizeObservation {
    constructor(Element target, ResizeObserverBoxOptions observedBox);
    readonly attribute Element target;
    readonly attribute ResizeObserverBoxOptions observedBox;
    readonly attribute FrozenArray&lt;ResizeObserverSize> lastReportedSizes;
};
</pre>
<div dfn-type="attribute" dfn-for="ResizeObservation">
    : <dfn>target</dfn>
    :: The observed {{Element}}.
    : <dfn>observedBox</dfn>
    :: Which box is being observed.
    : <dfn>lastReportedSizes</dfn>
    :: Ordered array of last reported sizes.
</div>
<div dfn-type="method" dfn-for="ResizeObservation">
    : <dfn constructor lt="ResizeObservation(target, options)">new ResizeObservation(target, observedBox)</dfn>
    ::
        1. Let |this| be a new {{ResizeObservation}} object.

        2. Set |this| internal {{ResizeObservation/target}} slot to |target|.

        3. Set |this| internal {{ResizeObservation/observedBox}} slot to |observedBox|.

        4. Set |this| internal {{ResizeObservation/lastReportedSizes}} slot to [(0,0)].

    : <dfn method lt="isActive()">isActive()</dfn>
    ::

        1. Set |currentSize| by <a>calculate box size</a> given |target| and |observedBox|.

        2. Return true if |currentSize| is not equal to the first entry in this.{{ResizeObservation/lastReportedSizes}}.

        3. Return false.

</div>

<h3 id="internal-slot-definitions">Internal Slot Definitions</h3>

<h4 id="document-slots">Document</h4>

<a>Document</a> has a <dfn attribute for="Document">\[[resizeObservers]]</dfn> slot that is a list of {{ResizeObserver}}s in this document. It is initialized to empty.

<h4 id="resize-observer-slots">ResizeObserver</h4>

{{ResizeObserver}} has a <dfn attribute for="ResizeObserver">\[[callback]]</dfn> slot, initialized by constructor.

{{ResizeObserver}} has an <dfn attribute for="ResizeObserver">\[[observationTargets]]</dfn> slot, which is a list of {{ResizeObservation}}s.
It represents all Elements being observed.

{{ResizeObserver}} has a <dfn attribute for="ResizeObserver">\[[activeTargets]]</dfn> slot, which is a list of {{ResizeObservation}}s. It represents all Elements whose size has changed since last observation broadcast that are eligible for broadcast.

{{ResizeObserver}} has a <dfn attribute for="ResizeObserver">\[[skippedTargets]]</dfn> slot, which is a list of {{ResizeObservation}}s. It represents all Elements whose size has changed since last observation broadcast that are <strong>not</strong> eligible for broadcast

<h3 id="css-definitions">CSS Definitions</h3>
<h4 id="content-rect-h">content rect</h4>
DOM <dfn>content rect</dfn> is a rect whose:

* width is <a>content width</a>
* height is <a>content height</a>
* top is <a>padding top</a>
* left is <a>padding left</a>

<a>content width</a> spec does not mention how <a>multi-column</a> layout affects content box. In this spec, content width of an {{Element}} inside <a>multi-column</a> is the result of ``getComputedStyle(element).width``. This currently evaluates to width of the first column.

Having content rect position be padding-top/left is useful for absolute positioning of target's children. Absolute position coordinate space origin is topLeft of the padding rect.

Watching content rect means that:

* observation will fire when watched Element is inserted/removed from DOM.

* observation will fire when watched Element display gets set to none.

* non-replaced inline Elements will always have an empty content rect.

* observations will not be triggered by CSS transforms.

Web content can also contain SVG elements. SVG elements that do not have associated CSS layout boxes define <a>bounding box</a> instead of a content box.
Content rect for the <a>SVGGraphicsElement</a>s without CSS layout boxes is a rect whose:

* width is <a>bounding box</a> width
* height is <a>bounding box</a> height
* top and left are 0

<h3 id="algorithms">Algorithms</h3>

<h4 id="gather-active-observations-h">Gather active resize observations at depth</h4>

It computes all active resize observations for a |document|. To <dfn>gather active resize observations at depth</dfn>, run these steps:

1. Let |depth| be the depth passed in.

1. For each |observer| in {{Document/[[resizeObservers]]}} run these steps:

    1. Clear |observer|'s {{ResizeObserver/[[activeTargets]]}}, and {{ResizeObserver/[[skippedTargets]]}}.

    2. For each |observation| in |observer|.{{ResizeObserver/[[observationTargets]]}} run this step:

        1. If |observation|.{{ResizeObservation/isActive()}} is true

            1. Let |targetDepth| be result of <a>calculate depth for node</a> for |observation|.{{ResizeObservation/target}}.

            2. If |targetDepth| is greater than |depth| then add |observation| to {{ResizeObserver/[[activeTargets]]}}.

            3. Else add |observation| to {{ResizeObserver/[[skippedTargets]]}}.

<h4 id="has-active-observations-h">Has active resize observations</h4>

To determine if {{Document}} <dfn>has active resize observations</dfn> run these steps:

1. For each |observer| in {{Document/[[resizeObservers]]}} run this step:

    1. If |observer|.{{ResizeObserver/[[activeTargets]]}} is not empty, return true.

2. return false.

<h4 id="has-skipped-observations-h">Has skipped resize observations</h4>

To determine if {{Document}} <dfn>has skipped resize observations</dfn> run these steps:

1. For each |observer| in {{Document/[[resizeObservers]]}} run this step:

    1. If |observer|.{{ResizeObserver/[[skippedTargets]]}} is not empty, return true.

2. return false.

<h4 id="create-and-populate-resizeobserverentry-h">
Create and populate a ResizeObserverEntry
</h4>
To <dfn>create and populate a ResizeObserverEntry</dfn> for a given |target|,
run these steps:
1. Let |this| be a new {{ResizeObserverEntry}}.

2. Set |this|.{{ResizeObserverEntry/target}} slot to |target|.

3. Set |this|.{{ResizeObserverEntry/borderBoxSize}} slot to result of <a>calculating box size</a>
            given |target| and observedBox of {{"border-box"}}.

4. Set |this|.{{ResizeObserverEntry/contentBoxSize}} slot to result of <a>calculating box size</a>
            given |target| and observedBox of {{"content-box"}}.

5. Set |this|.{{ResizeObserverEntry/devicePixelContentBoxSize}} slot to result of <a>calculating box size</a>
            given |target| and observedBox of {{"device-pixel-content-box"}}.

6. Set |this|.{{ResizeObserverEntry/contentRect}} to logical |this|.{{ResizeObserverEntry/contentBoxSize}} given |target| and observedBox of "content-box".

7. If |target| is not an SVG element or |target| is an SVG element with an associated CSS layout box do these steps:

    1. Set |this|.|contentRect|.top to |target|.<a>padding top</a>.

    2. Set |this|.|contentRect|.left to |target|.<a>padding left</a>.

8. If |target| is an SVG element without an associated CSS layout box do these steps:

    1. Set |this|.|contentRect|.top and |this|.contentRect.left to 0.

<h4 id="broadcast-resize-notifications-h">Broadcast active resize observations</h4>

<dfn>broadcast active resize observations</dfn> delivers all active resize
observations in a document, and returns the depth of the shallowest broadcast
target depth.

To broadcast active resize observations for a |document|, run these steps:

1. Let |shallowestTargetDepth| be ∞

2. For each |observer| in |document|.{{Document/[[resizeObservers]]}} run these steps:

    1. If |observer|.{{ResizeObserver/[[activeTargets]]}} slot is empty, continue.

    2. Let |entries| be an empty list of {{ResizeObserverEntry}}ies.

    3. For each |observation| in {{ResizeObserver/[[activeTargets]]}} perform these steps:

        1. Let |entry| be the result of running <a>create and populate a ResizeObserverEntry</a> given |observation|.{{ResizeObservation/target}}.

        2. Add |entry| to |entries|.

        3. Set |observation|.{{lastReportedSizes}} to matching |entry| sizes.

            1. Matching sizes are |entry|.{{ResizeObserverEntry/borderBoxSize}} if |observation|.{{ResizeObservation/observedBox}} is "border-box"

            2. Matching sizes are |entry|.{{ResizeObserverEntry/contentBoxSize}} if |observation|.{{ResizeObservation/observedBox}} is "content-box"

            3. Matching sizes are |entry|.{{ResizeObserverEntry/devicePixelContentBoxSize}} if |observation|.{{ResizeObservation/observedBox}} is "device-pixel-content-box"

        4. Set |targetDepth| to the result of <a>calculate depth for node</a> for |observation|.{{ResizeObservation/target}}.

        5. Set |shallowestTargetDepth| to |targetDepth| if |targetDepth| < |shallowestTargetDepth|

    4. Invoke |observer|.{{ResizeObserver/[[callback]]}} with |entries|.

    5. Clear |observer|.{{ResizeObserver/[[activeTargets]]}}.

3. Return |shallowestTargetDepth|.

<h4 id="deliver-resize-error">Deliver Resize Loop Error</h4>

To <dfn>deliver resize loop error notification</dfn> run these steps:

    1. Create a new {{ErrorEvent}}.

    2. Initialize |event|'s message slot to "ResizeObserver loop completed with undelivered notifications.".

    3. Report the exception |event|.

<h4 id="calculate-depth-for-node-h">Calculate depth for node</h4>

To <dfn>calculate depth for node</dfn>, given a |node|, run these steps:

    1. Let |p| be the parent-traversal path from |node| to a root Element of this element's flattened DOM tree.

    2. Return number of nodes in |p|.

<h4 id="calculate-box-size-h">Calculate box size, given target and observed box</h4>

This algorithm computes |target| {{Element}}'s observed box size. Type of box is
described by {{ResizeObserverBoxOptions}}.
The SVG elements which don't have associated CSS layout boxes are an exception. The sizes of these elements are always their bounding box sizes, because
these elements do not use standard CSS box model.

To <dfn>calculate box size</dfn>, given |target| and |observedBox|, run these steps:

    1. Let |computedSize| be a new {{ResizeObserverSize}} object.

    2. If |target| is an {{SVGGraphicsElement}} that does not have an associated CSS layout box:

        <dl class=switch>
          <dt>If |observedBox| is {{"border-box"}}

          <dt>If |observedBox| is {{"content-box"}}

          <dd>
            1. Set |computedSize|'s {{ResizeObserverSize/inlineSize}} attribute to |target|'s <a>bounding box</a> inline length.

            2. Set |computedSize|'s {{ResizeObserverSize/blockSize}} attribute to |target|'s <a>bounding box</a> block length.

          <dt>If |observedBox| is {{"device-pixel-content-box"}}

          <dd>
            1. Set |computedSize|'s {{ResizeObserverSize/inlineSize}} attribute to |target|'s <a>bounding box</a> inline length, in integral device pixels.

            2. Set |computedSize|'s {{ResizeObserverSize/blockSize}} attribute to |target|'s <a>bounding box</a> block length, in integral device pixels.
        </dl>

    3. Otherwise:

        <dl class=switch>
          <dt>If |observedBox| is {{"border-box"}}

          <dd>
            1. Set |computedSize|'s {{ResizeObserverSize/inlineSize}} attribute to |target|'s <a>border area</a> inline length.

            2. Set |computedSize|'s {{ResizeObserverSize/blockSize}} attribute to |target|'s <a>border area</a> block length.

          <dt>If |observedBox| is {{"content-box"}}

          <dd>
            1. Set |computedSize|'s {{ResizeObserverSize/inlineSize}} attribute to |target|'s <a>content area</a> inline length.

            2. Set |computedSize|'s {{ResizeObserverSize/blockSize}} attribute to |target|'s <a>content area</a> block length.

          <dt>If |observedBox| is {{"device-pixel-content-box"}}

          <dd>
            1. Set |computedSize|'s {{ResizeObserverSize/inlineSize}} attribute to |target|'s <a>content area</a> inline length, in integral device pixels.

            2. Set |computedSize|'s {{ResizeObserverSize/blockSize}} attribute to |target|'s <a>content area</a> block length, in integral device pixels.
        </dl>

    4. Return |computedSize|.

<h3 id="lifetime">ResizeObserver Lifetime</h3>

A {{ResizeObserver}} will remain alive until both of these conditions are met:

* there are no scripting references to the observer.

* the observer is not observing any targets.
